package core

import (
	"bytes"
	"log/slog"
	"logengine/internal/btree"
	"strconv"
)

var (
	tr *btree.BTree
)

func InitDataAddrTree(csvData []byte) {
	xyDataList := initDataAddrList(csvData)
	tr = btree.New(8)
	for _, data := range xyDataList {
		tr.ReplaceOrInsert(data)
	}
	slog.Warn("data_addr_btree:", "tr_len", tr.Len())
}

func initDataAddrList(csvData []byte) []*XYD {
	lines := bytes.Split(csvData, []byte("\n"))
	xyDataList := make([]*XYD, 0, len(lines))
	for _, line := range lines {
		t := bytes.Split(line, []byte(","))
		if len(t) < 3 {
			continue
		}
		_x, _ := strconv.Atoi(string(t[0]))
		_y, _ := strconv.Atoi(string(t[1]))
		_addr := string(t[2])
		tmp := &XYD{_x, _y, _addr}
		slog.Warn("data_addr:", "xy_data", tmp)
		xyDataList = append(xyDataList, tmp)
	}
	return xyDataList
}

type XYD struct {
	X    int
	Y    int
	Addr string
}

func (a *XYD) Less(_b btree.Item) bool {
	b := _b.(*XYD)
	if a.X < b.X {
		return true
	} else if a.X > b.X {
		return false
	}
	return a.Y < b.Y
}
